package com.wudgaby.study.jwtauth.support;

import com.wudgaby.study.jwtauth.dto.AuthUser;
import com.wudgaby.study.jwtauth.dto.TokenBean;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

public class SecurityContextHolder {
    /**
     * 自定义的threadlocal出现无法清理问题.
     */
    /*private static final ThreadLocal<TokenBean> tokenHolder = new NamedThreadLocal<>("token");
    private static final ThreadLocal<AuthUser> authUserHolder = new NamedThreadLocal<>("Auth User");*/

    /**
        RequestContextFilter清理threadlocal
     */
    /*public static void setAuthUser(@NonNull AuthUser authUser) {
        authUserHolder.set(authUser);
    }

    public static AuthUser getAuthUser() {
        return authUserHolder.get();
    }

    public static void setToken(@NonNull String accessToken, @Nullable String refreshToken){
        tokenHolder.set(new TokenBean(accessToken, refreshToken));
    }

    public static TokenBean getTokenBean() {
        return tokenHolder.get();
    }

    public static void clear() {
        authUserHolder.remove();
        tokenHolder.remove();
    }*/

    private static final String SECURITY_CONTEXT_ATTRIBUTES = "CONTEXT_AUTH_USER";
    private static final String TOKEN_CONTEXT_ATTRIBUTES = "CONTEXT_TOKEN";

    public static void setAuthUser(@NonNull AuthUser authUser) {
        RequestContextHolder.currentRequestAttributes().setAttribute(
                SECURITY_CONTEXT_ATTRIBUTES,
                authUser,
                RequestAttributes.SCOPE_REQUEST);
    }

    public static AuthUser getAuthUser() {
        return (AuthUser)RequestContextHolder.currentRequestAttributes()
                .getAttribute(SECURITY_CONTEXT_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);
    }

    public static void setToken(@NonNull String accessToken, @Nullable String refreshToken){
        RequestContextHolder.currentRequestAttributes().setAttribute(
                TOKEN_CONTEXT_ATTRIBUTES,
                new TokenBean(accessToken, refreshToken),
                RequestAttributes.SCOPE_REQUEST);
    }

    public static TokenBean getTokenBean() {
        return (TokenBean)RequestContextHolder.currentRequestAttributes()
                .getAttribute(TOKEN_CONTEXT_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);
    }
}
